<template>
	<view class="">
		<u-calendar ref="calendar"
			:value="show"
			:toolTip="label"
			:mode="type" 
			range-bg-color="rgba(238, 10, 36, .1)"
			:active-bg-color="color"
			:range-color="color"
			btn-type="primary"
			max-date="2050-01-01"
			@change="onSelectDate" @close="onClose"
		/>
	</view>
</template>

<script>
	const dayjs = require('dayjs');
	const customParseFormat = require('dayjs/plugin/customParseFormat');
	dayjs.extend(customParseFormat);

	export default {
		name: 'popupCalendar',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			value: {
				type: [String, Number, Date, Array]
			},
			label: {
				type: String
			},
			type: {
				type: String,
				default: 'single'
			},
			color: {
				type: String
			},
			confirmText: {
				type: String,
				default: '确定'
			},
			valueFormat: {
				type: String,
				default: 'YYYY-MM-DD'
			}
		},
		data() {
			return {
				currentDate: undefined
			}
		},
		methods: {
			onClose() {
				this.$emit('close');
			},
			onSelectDate(date) {
				this.$emit('input', [date.startDate, date.endDate]);
				this.$emit('close');
			},
		},
		computed: {
			day() {
				function formatDateValue(value, valueFormat) {
					if (valueFormat === 'timestamp') {
						// 时间戳
						return dayjs(value);
					} else if (typeof value === 'string') {
						return dayjs(value, valueFormat);
					} else {
						return dayjs(value);
					}
				}
				if (this.value == null) return null;
				if (Array.isArray(this.value)) {
					return this.value.map(item => {
						return formatDateValue(item, this.valueFormat);
					});
				} else {
					return formatDateValue(this.value, this.valueFormat);
				}
			}
		},
		watch: {
			day: {
				handler() {
					this.currentDate = this.day;
				},
				immediate: true
			}
		}
	}
</script>

<style>
</style>